
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define DB_NAME 	"ts-3.1.0.db"
#define SOFTWARE_NAME 	"tcp_server"
#define SERVER_PORT 8080         // 服务器端口
#define BACKLOG 5                // 最大监听队列

int main(int argc, char **argv)
{
  int port = 0;

  if (argc < 2) {
    printf("Usage: tcpserver <port>\n");
    exit(1);
  }
  port = atoi(argv[1]);
  int server_fd = socket(AF_INET, SOCK_STREAM, 0);
  if (server_fd == -1) {
      perror("Socket creation failed");
      exit(1);
  }

  struct sockaddr_in server_addr;
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = INADDR_ANY;  // 监听所有网络接口
  server_addr.sin_port = htons(port);

  if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
      perror("Bind failed");
      exit(1);
  }
  printf("Server is listening on port %d\n", port);

  // 4. 监听客户端连接
  if (listen(server_fd, BACKLOG) < 0) {
      perror("Listen failed");
      exit(1);
  }

  struct sockaddr_in client_addr;
  socklen_t client_len = sizeof(client_addr);
  int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
  if (client_fd < 0) {
      perror("Accept failed");
      exit(1);
  }
  printf("Connected to client: %s\n", inet_ntoa(client_addr.sin_addr));

  char buffer[1024];
  int n = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
  if (n < 0) {
      perror("Receive failed");
      exit(1);
  }
  buffer[n] = '\0';  // 确保接收到的消息是一个以 '\0' 结尾的字符串
  printf("Received from client: %s\n", buffer);

  //const char *response = "Hello from TCP server!";
  const char *response = "1234567890123456\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<PatrolDevice>\
<Type>1002</Type>\
<Command>1</Command>\
<Time>2023-01-01 00:00:01</Time>\
<Items>\
<MotionState>0</MotionState>\
<PosX>0.0</PosX>\
<PosY>2.0</PosY>\
<PosZ>0.0</PosZ>\
<Roll>0.0</Roll>\
<Pitch>0.0</Pitch>\
<Yaw>0.0</Yaw>\
<Speed>0.0</Speed>\
<CurOdom>0.0</CurOdom>\
<SumOdom>0.0</SumOdom>\
<Res>0.0</Res>\
<X0>0.0</X0>\
<Y0>0.0</Y0>\
<H>1000</H>\
<Electricity>50</Electricity>\
<Location>0</Location>\
<GaitState>0</GaitState>\
<MotorState>0</MotorState>\
<ChargeState>0</ChargeState>\
<ControlMode>0</ControlMode>\
<OnDockState>0</OnDockState>\
</Items>\
</PatrolDevice>\
";
 //   Hello from TCP server!";
  if (send(client_fd, response, strlen(response), 0) < 0) {
      perror("Send failed");
      exit(1);
  }
  printf("Response sent to client: %s\n", response);

  close(client_fd);
  close(server_fd);
  return 0;
}
